<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-30 15:16:05
 * @LastEditTime: 2022-01-11 13:11:40
 * @LastEditors: Liz.Zheng
 * @Description: 添加水印
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    :maskClosable="false"
    :visible="visible"
    :destroyOnClose="true"
    :width="700"
    :body-style="{ paddingBottom: '60px' }"
    @close="closeModal"
    class="add-watermark"
  >
    <a-form layout="vertical">
      <a-card size="small" title="水印信息">
        <a-row type="flex" :gutter="24">
          <a-col flex="auto">
            <a-form-item label="水印名称" v-bind="validateInfos.name">
              <a-input placeholder="请输入" v-model:value="modelRef.name" />
            </a-form-item>
            <a-form-item label="上传水印图片" v-bind="validateInfos.image_path">
              <a-upload
                :action="$utils.imgAction"
                :headers="{ 'org-token': $store.getters.token }"
                :multiple="false"
                v-model:file-list="fileList"
                @change="handleUploadChange"
                name="image"
                :data="{ dir: 'org_watermark' }"
                accept="image/jpg,image/jpeg,image/gif,image/png"
                list-type="picture-card"
                :show-upload-list="false"
              >
                <img
                  v-if="modelRef.image_path"
                  :src="modelRef.image_path"
                  alt="watermark"
                  class="watermark-img"
                />
                <div v-else>
                  <plus-outlined></plus-outlined>
                  <div class="upload-tip">点击上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item label="缩放比例" v-bind="validateInfos.scale">
              <a-radio-group
                v-model:value="modelRef.scale"
                @change="handleScaleChange"
              >
                <a-radio-button value="0">默认</a-radio-button>
                <a-radio-button value="50">50%</a-radio-button>
                <a-radio-button value="100">100%</a-radio-button>
                <a-radio-button value="150">150%</a-radio-button>
                <a-radio-button value="200">200%</a-radio-button>
                <a-radio-button value="500">500%</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col flex="240px">
            <section class="a4-page">
              <img
                v-if="modelRef.image_path"
                :src="modelRef.image_path"
                :style="watermarkStyle"
              />
              <span v-else>预览区域</span>
            </section>
          </a-col>
        </a-row>
      </a-card>
      <a-card size="small" class="mt-20" title="关联模板">
        <a-form-item label="选择模板" v-bind="validateInfos.template_id">
          <a-select
            v-model:value="modelRef.template_id"
            mode="multiple"
            :options="templateList"
            placeholder="请选择"
          ></a-select>
        </a-form-item>
      </a-card>
    </a-form>
    <div class="drawer-footer">
      <a-button @click.prevent="closeModal" class="mr-10">关闭</a-button>
      <a-button type="primary" @click.prevent="onSubmit" :loading="submiting">
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  reactive,
  toRaw,
  nextTick,
} from "vue";
import { Form, message } from "ant-design-vue";
import request from "../../../../common/utils/request";
import { PlusOutlined } from "@ant-design/icons-vue";
import utils from "../../../../common/utils/utils";

const useForm = Form.useForm;

export default defineComponent({
  name: "watermarkAdd",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  components: { PlusOutlined },
  setup(props, context) {
    //   标题
    const title = computed(() => {
      return props.id ? "编辑水印" : "添加水印";
    });

    // 图片上传
    const fileList = ref([]);
    let imgSize = { width: 0, height: 0 };
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              modelRef.image_path = file.url;
              utils.getImageSize(modelRef.image_path).then((res) => {
                imgSize.width = res.width;
                imgSize.height = res.height;
                handleScaleChange();
              });
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.image_path = "";
        imgSize = { width: 0, height: 0 };
      }
      fileList.value = resFileList;
    };

    // 缩放比例
    const watermarkStyle = ref("");
    const handleScaleChange = () => {
      const imgWidth =
        modelRef.scale == 0
          ? imgSize.width
          : (imgSize.width * modelRef.scale) / 100;
      const imgHeight =
        modelRef.scale == 0
          ? imgSize.height
          : (imgSize.height * modelRef.scale) / 100;
      watermarkStyle.value = `width: ${imgWidth}px;height: ${imgHeight}px;`;
    };

    // 选择模板
    const templateList = ref([]);
    const getTemplate = () => {
      request.get("/org", "//contract/getPrintList").then((res) => {
        templateList.value = res.list.map((item) => ({
          value: item.id,
          label: item.template_name,
        }));
      });
    };

    /**
     * @description:  表单
     */
    const modelRef = reactive({
      name: "",
      scale: "0",
      image_path: "",
      template_id: [],
    });
    const rulesRef = reactive({
      name: [{ required: true, message: "请输入水印名称" }],
      image_path: [{ required: true, message: "请上传水印图片" }],
      scale: [{ required: true, message: "请选择图片比例" }],
      template_id: [{ required: true, message: "请选择合同模板" }],
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const closeModal = () => {
      context.emit("cancel");
    };

    const submiting = ref(false);
    const onSubmit = () => {
      validate().then(() => {
        submiting.value = true;
        let params = { ...modelRef, needMsg: true };
        params.template_id = params.template_id.join(",");
        params.scale_size = watermarkStyle.value;
        // console.log("........params", params);
        let requestMethod = "post";
        let requestUrl = "/contract/watermark";
        if (props.id) {
          params.id = props.id;
          requestMethod = "put";
        }
        const success = (res) => {
          message.success(res.msg || "保存成功");
          context.emit("success");
        };
        request[requestMethod]("/org", requestUrl, params)
          .then((res) => success(res))
          .finally(() => {
            submiting.value = false;
          });
      });
    };

    const getDetail = () => {
      request
        .get("/org", "/contract/watermarkDetail", {
          id: props.id,
        })
        .then((res) => {
          const { detail } = res;
          modelRef.name = detail.name;
          modelRef.scale = detail.scale;
          modelRef.image_path = detail.image_path;
          modelRef.template_id = detail.template_json.map(
            (item) => item.template_id
          );
          utils.getImageSize(modelRef.image_path).then((res) => {
            imgSize.width = res.width;
            imgSize.height = res.height;
            handleScaleChange();
          });
        });
    };

    // 初始化
    const init = () => {
      getTemplate();
      if (props.id) {
        getDetail();
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          fileList.value = [];
        }
      }
    );

    return {
      title,
      modelRef,
      validateInfos,
      submiting,
      fileList,
      watermarkStyle,
      templateList,
      handleUploadChange,
      closeModal,
      onSubmit,
      handleScaleChange,
    };
  },
});
</script>

<style lang="less" scoped>
.add-watermark {
  .a4-page {
    border: 2px solid #ccc;
    width: 210px;
    height: 297px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: rgba(0, 0, 0, 0.3);
    overflow: hidden;
  }
  .watermark-img {
    width: 100px;
    height: 100px;
  }
  .upload-tip {
    font-size: 12px;
    color: #999;
  }
}
</style>
